package com.shop.shop_end.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shop.shop_end.entity.User;
import com.shop.shop_end.exception.ServiceException;
import com.shop.shop_end.mapper.UserMapper;
import com.shop.shop_end.service.UserService;
import com.shop.shop_end.utils.*;
import com.shop.shop_end.utils.result.Result;
import com.shop.shop_end.utils.result.ResultUtil;
import com.shop.shop_end.variable.EnableVariable;
import com.shop.shop_end.dto.RegisterUser;
import com.shop.shop_end.variable.ErrorCodeEnum;
import com.shop.shop_end.variable.RoleVariable;
import com.shop.shop_end.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Resource
    private UserMapper userMapper;

    @Resource
    private CommonUtil commonUtil;
//    @Resource
//    private ImagesMapper imagesMapper;

    /**
     * 获取所有用户信息
     * @return
     */
    @Override
    public List<UserVo> getAllUserList() {
        List<UserVo> userVoList = new ArrayList<>();
        List<User> userList = userMapper.selectList(new QueryWrapper<>());
        userList.forEach((item)->{
            UserVo userVo = new UserVo();
            userVo.setUserId(item.getUserId());
            userVo.setUsername(item.getUsername());
            userVo.setPassword(item.getPassword());
            userVo.setGender(item.getGender());
            userVo.setContact(item.getContact());
            userVo.setRealName(item.getRealName());
            userVo.setAvatar(item.getAvatar());
            userVo.setBirthday(DateUtils.format(item.getBirthday()));
            userVo.setCreateTime(DateUtils.format(item.getCreateTime(), DateUtils.DATE_TIME_PATTERN));
            userVo.setEnable(item.getEnable());
            userVoList.add(userVo);
        });
        logger.info("userVoList==>{}", userVoList);
        return userVoList;
    }


    /**
     * 注册
     * @param registerUser
     * @return
     */
    @Override
    @Transactional
    public Result register(RegisterUser registerUser) {//少了密码加密
        try {
            logger.info("registerUser==>{}", registerUser);
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("username", registerUser.getUsername());
            User isExistUser = userMapper.selectOne(wrapper);//判断用户名是否已经存在
            if (isExistUser != null){
                logger.info("已经存在此用户名，username：{}", registerUser.getUsername());
                return ResultUtil.error("已经存在此用户名", registerUser.getUsername());
            }else {
                User user = new User();
                user.setUserId(GenerateIdUtil.generateId());//生成Id
                user.setUsername(registerUser.getUsername());
                String md5 = MD5Util.generateMD5(registerUser.getPassword());//密码加密
                user.setPassword(md5);
                user.setRealName(registerUser.getRealName());//真实姓名
                user.setGender(registerUser.getGender());//性别
                user.setBirthday(registerUser.getBirthday());//生日
                user.setContact(registerUser.getContact());//联系方式
                user.setEnable(EnableVariable.ENABLE);
                user.setCreateTime(new Date());
                int res = userMapper.insert(user);
                if (res == 1){
                    return ResultUtil.ok(user);
                }else {
                    logger.info("增加用户时出现异常，user：{}", user);
                    return ResultUtil.fail("注册出现异常，请重试", user);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.info("注册出现异常");
            throw new ServiceException(ErrorCodeEnum.SQL_INSERT_ERROR, "数据库增加用户失败");
        }
    }

    /**
     * 根据关键词来搜索用户
     * @param keyword
     * @return
     */
    @Override
    public Result getAllUserByKeyword(String keyword) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.like("username", keyword);
        List<User> userList = userMapper.selectList(wrapper);
        if (userList == null || userList.size() == 0){
            return ResultUtil.ok("数据为空");
        }
        return ResultUtil.ok(userList);
    }

    @Override
    public User getUserById(Long id) {
        return userMapper.selectById(id);
    }

    /**
     * 用户登录
     * @param username
     * @param password
     * @return
     */
    public Result login(String username, String password) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        User isExistUser = userMapper.selectOne(wrapper);
        if (isExistUser == null){
            logger.info("该用户名不存在，username：{}", username);
            return ResultUtil.error("该用户名不存在", username);
        }
        wrapper = new QueryWrapper<>();
        //密码加密
        String md5 = MD5Util.generateMD5(password);
        wrapper.eq("username", username).eq("password", md5);
        User res = userMapper.selectOne(wrapper);//登录结果
        if (res == null){
            logger.info("登录失败，密码错误");
            return ResultUtil.fail("登录失败，密码错误");
        }
        if (res.getEnable() == EnableVariable.UNABLE){//无效，被封禁
            logger.info("该用户已被封禁，登录失败，username：{}", username);
            return ResultUtil.fail("改账号已被封禁，请联系管理员解封后登录！");
        }
//        QueryWrapper<Images> wrapper2 = new QueryWrapper<>();
//        QueryWrapper<Images> wrapper3 = new QueryWrapper<>();
//        //查询头像
//        wrapper2.eq("type", ImageVariable.IMAGE_AVATAR).eq("iid", res.getId());
//        Images avatar = imagesMapper.selectOne(wrapper2);
//        //查询背景图片
//        wrapper3.eq("type", ImageVariable.IMAGE_BG).eq("iid", res.getId());
//        List<Images> bannerList = imagesMapper.selectList(wrapper3);
//        UserVo userVo = UserVoInUtil.getUserVo(res, avatar, bannerList);//返回的用户信息
//        System.out.println(userVo);
        UserVo userVo = new UserVo();
        logger.info("用户：{} 登录成功", username);
        //TODO
        userVo.setUserId(res.getUserId());
        userVo.setUsername(res.getUsername());
        userVo.setRealName(res.getRealName());
        userVo.setPassword(res.getPassword());
        userVo.setAvatar(res.getAvatar());
        userVo.setGender(res.getGender());
        userVo.setContact(res.getContact());
        userVo.setBirthday(DateUtils.format(res.getBirthday()));
        userVo.setCreateTime(DateUtils.format(res.getCreateTime(), DateUtils.DATE_TIME_PATTERN));
        userVo.setEnable(res.getEnable());
        //生成token
        String token = TokenUtils.generateToken(userVo.getUserId(), RoleVariable.ROLE_USER, userVo.getPassword());
        userVo.setToken(token);
        this.commonUtil.getSession().setAttribute("user", userVo);
        return ResultUtil.ok().setDesc("登录成功").setData(userVo);
    }

    /**
     * 删除用户
     * @param id
     */
    public Result deleteUserById(Long id){
        User isExistUser = userMapper.selectById(id);
        if (isExistUser == null){
            logger.info("该用户已不存在，删除失败");
            return ResultUtil.error("该用户已不存在，删除失败");
        }
        Integer res = userMapper.deleteById(id);
        if (res <= 0 || res == null){
            logger.info("删除信息出现异常，user==>{}", isExistUser);
            return ResultUtil.error("删除信息时出现未知异常", isExistUser);
        }
        logger.info("用户删除成功，user==>{}", isExistUser);
        return ResultUtil.ok("删除成功", isExistUser);
    }

    /**
     * 修改用户信息
     * @param user
     */
    @Override
    @Transactional
    public Result updateUserById(User user){
        User isExistUser = userMapper.selectById(user.getUserId());
        if (isExistUser == null){
            logger.info("该用户已不存在，删除失败");
            return ResultUtil.error("该用户已不存在，删除失败");
        }
        Integer res = userMapper.updateById(user);
        if (res <= 0 || res == null){
            logger.info("修改用户信息失败，user==>{}", user);
            return ResultUtil.error("修改信息时出现未知异常", user);
        }
        logger.info("修改用户信息成功，user==>{}", user);
        return ResultUtil.ok(user).setDesc("修改成功");
    }

    //    /**
//     * 获取好友列表
//     * @param id
//     * @return
//     */
//    @Override
//    public Result getMyInterrelatedList(Long id) {
//        //关联表查询
//        List<User> userList = userMapper.selectFriList(id);
//        List<UserVo> userVoList = new ArrayList<>();
//        //补全信息，如头像，背景图片。。。
//        for (User user : userList) {
//            QueryWrapper<Images> wrapper2 = new QueryWrapper<>();
//            QueryWrapper<Images> wrapper3 = new QueryWrapper<>();
//            //查询头像
//            wrapper2.eq("type", ImageVariable.IMAGE_AVATAR).eq("iid", user.getId());
//            Images avatar = imagesMapper.selectOne(wrapper2);
//            //查询背景图片
//            wrapper3.eq("type", ImageVariable.IMAGE_BG).eq("iid", user.getId());
//            List<Images> bannerList = imagesMapper.selectList(wrapper3);
//            UserVo userVo = UserVoInUtil.getUserVo(user, avatar, bannerList);//返回的用户信息
//            userVoList.add(userVo);
//        }
//        return ResultUtil.ok(userVoList);
//    }

//    /**
//     * 查询用户详情，包括用户个人信息，背景图片，发布的动态等等
//     * @param id 用户id
//     * @return
//     */
//    @Override
//    public Result getUserDetail(Long id) {
//        Map<String, Object> returnMap = new HashMap<>();
//        User user = userMapper.selectById(id);
//        QueryWrapper<Images> wrapper = new QueryWrapper<>();
//        wrapper.eq("type", ImageVariable.IMAGE_AVATAR)
//                .eq("iid", id);
//        //1、获取头像
//        Images avatar = imagesMapper.selectOne(wrapper);
//        //2、获取背景图片
//        QueryWrapper<Images> wrapper1 = new QueryWrapper<>();
//        wrapper1.eq("type", ImageVariable.IMAGE_BG)
//                .eq("iid", id);
//        List<Images> bannerList = imagesMapper.selectList(wrapper1);
//        UserVo userVo = UserVoInUtil.getUserVo(user, avatar, bannerList);//返回的用户信息
//        //3、获取动态
//        List<DynamicVo> dynamicVoList = dynamicService.getMyDynamicList(id);
//        //将用户信息和动态信息放入
//        returnMap.put("user", userVo);
//        returnMap.put("dynamicList", dynamicVoList);
//        return ResultUtil.ok(returnMap);
//    }
}
